package com.xunker.order.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xunker.appointment.enums.EmailCodeTemplate;
import com.xunker.appointment.enums.OrderStatusEnum;
import com.xunker.appointment.exception.AppointmentException;
import com.xunker.appointment.model.orderinfo.OrderInfo;
import com.xunker.appointment.model.patient.Patient;
import com.xunker.appointment.result.ResultCodeEnum;
import com.xunker.appointment.utils.BeanUtils;
import com.xunker.appointment.utils.HttpRequestHelper;
import com.xunker.appointment.vo.mq.EmailVo;
import com.xunker.appointment.vo.mq.OrderMqVo;
import com.xunker.appointment.vo.order.*;
import com.xunker.client.HospitalFeignClient;
import com.xunker.client.PatientFeignClient;
import com.xunker.order.mapper.OrderMapper;
import com.xunker.order.service.OrderService;
import com.xunker.order.service.WeChatPayService;
import com.xunker.rabbit.constant.MqConst;
import com.xunker.rabbit.service.RabbitService;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.stream.Collectors;

@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, OrderInfo> implements OrderService {
    @Autowired
    private RabbitService rabbitService;
    @Autowired
    private PatientFeignClient patientFeignClient;
    @Autowired
    private HospitalFeignClient hospitalFeignClient;
    @Autowired
    private WeChatPayService weChatPayService;
    @Override
    public Long saveOrder(String scheduleId, String patientId) {
        Patient iPatient = patientFeignClient.getIPatient(Long.parseLong(patientId));
        if(null == iPatient) {
            throw new AppointmentException(ResultCodeEnum.PARAM_ERROR);
        }
        ScheduleOrderVo scheduleOrderVo = hospitalFeignClient.getScheduleOrderVo(Long.parseLong(scheduleId));
        if(null == scheduleOrderVo) {
            throw new AppointmentException(ResultCodeEnum.PARAM_ERROR);
        }
        //当前时间不可以预约
        if(new DateTime(scheduleOrderVo.getStartTime()).isAfterNow()|| new DateTime(scheduleOrderVo.getEndTime()).isBeforeNow()) {
            throw new AppointmentException(ResultCodeEnum.TIME_NO);
        }
        SignInfoVo signInfoVo = hospitalFeignClient.getSignInfoVo(scheduleOrderVo.getHospitalCode());
        if(null == signInfoVo) {
            throw new AppointmentException(ResultCodeEnum.PARAM_ERROR);
        }
        if(scheduleOrderVo.getAvailableNumber() <= 0) {
            throw new AppointmentException(ResultCodeEnum.NUMBER_NO);
        }
        OrderInfo orderInfo = new OrderInfo();
        BeanUtils.copyProperties(scheduleOrderVo, orderInfo);
        String outTradeNo = System.currentTimeMillis() + ""+ new Random().nextInt(100);
        orderInfo.setOutTradeNo(outTradeNo);
        orderInfo.setScheduleId(scheduleId);
        orderInfo.setUserId(iPatient.getUserId());
        orderInfo.setPatientId(Long.parseLong(patientId));
        orderInfo.setPatientName(iPatient.getName());
        orderInfo.setPatientPhone(iPatient.getPhone());
        orderInfo.setEmail(iPatient.getEmail());
        orderInfo.setOrderStatus(OrderStatusEnum.UNPAID.getStatus());
        this.save(orderInfo);

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("hospitalCode",orderInfo.getHospitalCode());
        paramMap.put("departmentCode",orderInfo.getDepartmentCode());
        paramMap.put("hosScheduleId",orderInfo.getScheduleId());
        paramMap.put("reserveDate",new DateTime(orderInfo.getReserveDate()).toString("yyyy-MM-dd"));
        paramMap.put("reserveTime", orderInfo.getReserveTime());
        paramMap.put("amount",orderInfo.getAmount());
        paramMap.put("name", iPatient.getName());
        paramMap.put("certificatesType",iPatient.getCertificatesType());
        paramMap.put("certificatesNo", iPatient.getCertificatesNo());
        paramMap.put("sex",iPatient.getSex());
        paramMap.put("birthdate", new DateTime(iPatient.getBirthdate()).toString("yyyy-MM-dd"));
        paramMap.put("phone",iPatient.getPhone());
        paramMap.put("email",iPatient.getEmail());
        paramMap.put("isMarry", iPatient.getIsMarry());
        paramMap.put("provinceCode",iPatient.getProvinceCode());
        paramMap.put("cityCode", iPatient.getCityCode());
        paramMap.put("districtCode",iPatient.getDistrictCode());
        paramMap.put("address",iPatient.getAddress());
        //联系人
        paramMap.put("contactsName",iPatient.getContactsName());
        paramMap.put("contactsCertificatesType", iPatient.getContactsCertificatesType());
        paramMap.put("contactsCertificatesNo",iPatient.getContactsCertificatesNo());
        paramMap.put("contactsPhone",iPatient.getContactsPhone());
        paramMap.put("timestamp", HttpRequestHelper.getTimestamp());
        String sign = HttpRequestHelper.getSign(paramMap, signInfoVo.getSignKey());
        paramMap.put("sign", sign);
        JSONObject result = HttpRequestHelper.sendRequest(paramMap, signInfoVo.getApiUrl()+"/order/submitOrder");

        if(result.getInteger("code") == 200) {
            JSONObject jsonObject = result.getJSONObject("data");
            //预约记录唯一标识（医院预约记录主键）
            String hosRecordId = jsonObject.getString("hosRecordId");
            //预约序号
            Integer number = jsonObject.getInteger("number");
            //取号时间
            String fetchTime = jsonObject.getString("fetchTime");
            //取号地址
            String fetchAddress = jsonObject.getString("fetchAddress");
            //更新订单
            orderInfo.setHosRecordId(hosRecordId);
            orderInfo.setNumber(number);
            orderInfo.setFetchTime(fetchTime);
            orderInfo.setFetchAddress(fetchAddress);
            baseMapper.updateById(orderInfo);
            //排班约数
            Integer reservedNumber = jsonObject.getInteger("reservedNumber");
            //排班剩余预约数
            Integer availableNumber = jsonObject.getInteger("availableNumber");
            //发送mq信息更新号源和邮箱通知
            //发送mq信息更新号源
            OrderMqVo orderMqVo = new OrderMqVo();
            orderMqVo.setScheduleId(scheduleId);
            orderMqVo.setReservedNumber(reservedNumber);
            orderMqVo.setAvailableNumber(availableNumber);

            //邮箱提示
            EmailVo emailVo = new EmailVo();
            emailVo.setEmail(orderInfo.getEmail());
            emailVo.setTemplateCode(EmailCodeTemplate.E00002.getMsg());
            String reserveDate = new DateTime(orderInfo.getReserveDate()).toString("yyyy-MM-dd") + (orderInfo.getReserveTime()==0 ? "上午": "下午");
            Map<String,Object> param = new HashMap<String,Object>(){
                {
                    put("title", orderInfo.getHospitalName()+"|"+orderInfo.getDepartmentName()+"|"+orderInfo.getTitle());
                    put("amount", orderInfo.getAmount());
                    put("reserveDate", reserveDate);
                    put("name", orderInfo.getPatientName());
                    put("quitTime", new DateTime(orderInfo.getQuitTime()).toString("yyyy-MM-dd HH:mm"));
                }
            };
            emailVo.setParam(param);
            orderMqVo.setEmailVo(emailVo);
            //rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_EMAIL, MqConst.ROUTING_EMAIL_ITEM, emailVo);
            rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_ORDER, MqConst.ROUTING_ORDER, orderMqVo);
        } else {
            throw new AppointmentException(result.getString("message"), ResultCodeEnum.FAIL.getCode());
        }
        return orderInfo.getId();
    }

    @Override
    public OrderInfo getOrder(String orderId) {
        OrderInfo orderInfo = baseMapper.selectById(orderId);
        if(orderInfo==null){
            throw new AppointmentException(ResultCodeEnum.PARAM_ERROR);
        }
        orderInfo.setParam( new HashMap<String,Object>(){
            {
                put("orderStatusString",OrderStatusEnum.getStatusNameByStatus(orderInfo.getOrderStatus()));
            }
        });
        return orderInfo;
    }

    @Override
    public IPage<OrderInfo> getPage(Page<OrderInfo> objectPage, OrderQueryVo orderQueryVo) {
        //orderQueryVo获取条件值
        String name = orderQueryVo.getKeyword(); //医院名称
        Long patientId = orderQueryVo.getPatientId(); //就诊人名称
        String orderStatus = orderQueryVo.getOrderStatus(); //订单状态
        String reserveDate = orderQueryVo.getReserveDate();//安排时间
        String createTimeBegin = orderQueryVo.getCreateTimeBegin();
        String createTimeEnd = orderQueryVo.getCreateTimeEnd();
        //对条件值进行非空判断
        QueryWrapper<OrderInfo> wrapper = new QueryWrapper<>();
        if(!StringUtils.isEmpty(name)) {
            wrapper.like("hospital_name",name);
        }
        if(!StringUtils.isEmpty(patientId)) {
            wrapper.eq("patient_id",patientId);
        }
        if(!StringUtils.isEmpty(orderStatus)) {
            wrapper.eq("order_status",orderStatus);
        }
        if(!StringUtils.isEmpty(reserveDate)) {
            wrapper.ge("reserve_date",reserveDate);
        }
        if(!StringUtils.isEmpty(createTimeBegin)) {
            wrapper.ge("create_time",createTimeBegin);
        }
        if(!StringUtils.isEmpty(createTimeEnd)) {
            wrapper.le("create_time",createTimeEnd);
        }
        //调用mapper的方法
        IPage<OrderInfo> pages = baseMapper.selectPage(objectPage, wrapper);
        //编号变成对应值封装
        pages.getRecords().stream().forEach(item -> {
            item.setParam( new HashMap<String,Object>(){
                {
                    put("orderStatusString",OrderStatusEnum.getStatusNameByStatus(item.getOrderStatus()));
                }
            });
        });
        return pages;
    }

    @Override
    public Boolean cancelOrder(Long orderId) {
        //1.获取订单信息
        OrderInfo orderInfo = this.getById(orderId);
        //2.判断时间，当前时间大约退号时间，不能取消预约
        DateTime quitTime = new DateTime(orderInfo.getQuitTime());
        if(quitTime.isBeforeNow()) {
            throw new AppointmentException(ResultCodeEnum.CANCEL_ORDER_NO);
        }
        //3.调用预约接口，取消预约订单
        SignInfoVo signInfoVo = hospitalFeignClient.getSignInfoVo(orderInfo.getHospitalCode());
        if(null == signInfoVo) {
            throw new AppointmentException(ResultCodeEnum.PARAM_ERROR);
        }
        Map<String, Object> reqMap = new HashMap<>();
        reqMap.put("hospitalCode",orderInfo.getHospitalCode());
        reqMap.put("hosRecordId",orderInfo.getHosRecordId());
        reqMap.put("timestamp", HttpRequestHelper.getTimestamp());
        String sign = HttpRequestHelper.getSign(reqMap, signInfoVo.getSignKey());
        reqMap.put("sign", sign);
        //更新订单
        JSONObject result = HttpRequestHelper.sendRequest(reqMap, signInfoVo.getApiUrl()+"/order/updateCancelStatus");

        if(result.getInteger("code") != 200) {
            throw new AppointmentException(result.getString("message"), ResultCodeEnum.FAIL.getCode());
        } else {
            //是否支付 退款
            if(orderInfo.getOrderStatus().intValue() == OrderStatusEnum.PAID.getStatus().intValue()) {
                //已支付 退款
                boolean isRefund = weChatPayService.refund(orderId);
                if(!isRefund) {
                    throw new AppointmentException(ResultCodeEnum.CANCEL_ORDER_FAIL);
                }
            }
            //更改订单状态
            orderInfo.setOrderStatus(OrderStatusEnum.CANCLE.getStatus());
            this.updateById(orderInfo);
            //发送mq邮箱更新预约数 我们与下单成功更新预约数使用相同的mq信息，不设置可预约数与剩余预约数，接收端可预约数减1即可
            OrderMqVo orderMqVo = new OrderMqVo();
            orderMqVo.setScheduleId(orderInfo.getScheduleId());
            //短信提示
            /*MsmVo msmVo = new MsmVo();
            msmVo.setPhone(orderInfo.getPatientPhone());
            msmVo.setTemplateCode("SMS_194640722");*/
            //邮箱提示
            EmailVo emailVo = new EmailVo();
            emailVo.setEmail(orderInfo.getEmail());
            emailVo.setTemplateCode(EmailCodeTemplate.E00003.getMsg());
            String reserveDate = new DateTime(orderInfo.getReserveDate()).toString("yyyy-MM-dd") + (orderInfo.getReserveTime()==0 ? "上午": "下午");
            Map<String,Object> param = new HashMap<String,Object>(){{
                put("title", orderInfo.getHospitalName()+"|"+orderInfo.getDepartmentName()+"|"+orderInfo.getTitle());
                put("reserveDate", reserveDate);
                put("name", orderInfo.getPatientName());
            }};
            emailVo.setParam(param);
            orderMqVo.setEmailVo(emailVo);
            rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_ORDER, MqConst.ROUTING_ORDER, orderMqVo);
        }
        return true;
    }

    @Override
    public void patientTips() {
        QueryWrapper<OrderInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("reserve_date",new DateTime().toString("yyyy-MM-dd"));
        queryWrapper.ne("order_status",OrderStatusEnum.CANCLE.getStatus());
        List<OrderInfo> orderInfoList = baseMapper.selectList(queryWrapper);
        for(OrderInfo orderInfo : orderInfoList) {
            //邮箱提示
            EmailVo emailVo = new EmailVo();
            emailVo.setEmail(orderInfo.getEmail());
            emailVo.setTemplateCode(EmailCodeTemplate.E00002.getMsg());
            String reserveDate = new DateTime(orderInfo.getReserveDate()).toString("yyyy-MM-dd") + (orderInfo.getReserveTime()==0 ? "上午": "下午");
            Map<String,Object> param = new HashMap<String,Object>(){
                {
                    put("title", orderInfo.getHospitalName()+"|"+orderInfo.getDepartmentName()+"|"+orderInfo.getTitle());
                    put("reserveDate", reserveDate);
                    put("name", orderInfo.getPatientName());
                }
            };
            emailVo.setParam(param);
            rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_EMAIL, MqConst.ROUTING_EMAIL_ITEM, emailVo);
        }
    }
    @Override
    public Map<String, Object> getCountMap(OrderCountQueryVo orderCountQueryVo) {
        Map<String, Object> map = new HashMap<>();

        List<OrderCountVo> orderCountVoList
                = baseMapper.selectOrderCount(orderCountQueryVo);
        //日期列表
        List<String> dateList
                =orderCountVoList.stream().map(OrderCountVo::getReserveDate).collect(Collectors.toList());
        //统计列表
        List<Integer> countList
                =orderCountVoList.stream().map(OrderCountVo::getCount).collect(Collectors.toList());        //统计列表
        List<Integer> totalAmountList
                =orderCountVoList.stream().map(OrderCountVo::getTotalAmount).collect(Collectors.toList());
        map.put("dateList", dateList);
        map.put("countList", countList);
        map.put("totalAmountList", totalAmountList);
        return map;
    }
}
